package com.easyban.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easyban.common.BaseContext;
import com.easyban.common.R;
import com.easyban.entity.Guestbook;
import com.easyban.service.GuestbookService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Objects;

@RestController
@RequestMapping("/guestbook")
@Slf4j
public class GuestbookController {
    @Autowired
    private GuestbookService guestbookService;

    @PostMapping
    public R<String> addGuestbook(@RequestBody Guestbook guestbook) {
        guestbook.setStatus(0);
        guestbookService.save(guestbook);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page<Guestbook>> getGuestbookPage(int page, int pageSize, String name) {
        log.info("执行分页查询....");
        //构造分页构造器
        Page<Guestbook> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Guestbook> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(StringUtils.isNoneEmpty(name), Guestbook::getUserName, name);

        queryWrapper.orderByDesc(Guestbook::getCreateTime);

        guestbookService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    @DeleteMapping("/userDel")
    public R<String> userDelGuestbook(@RequestBody Guestbook guestbook) {
        if(!guestbook.getUserId().equals(BaseContext.getCurrentId())) return R.error("用户id不一致");

        guestbookService.removeById(guestbook.getId());

        return R.success("删除成功");
    }

    @GetMapping("/{id}")
    public R<Guestbook> getGuestbookById(@PathVariable Long id) {
        return R.success(guestbookService.getById(id));
    }

    @PutMapping
    public R<String> updateGuestbook(@RequestBody Guestbook guestbook) {
        guestbook.setStatus(1);
        guestbook.setReplyUserId(BaseContext.getCurrentId());
        guestbook.setReplyTime(LocalDateTime.now());
        guestbookService.updateById(guestbook);
        return R.success("回复成功");
    }

    @DeleteMapping
    public R<String> delGuestbook(@RequestBody Guestbook guestbook) {

        guestbookService.removeById(guestbook.getId());

        return R.success("删除成功");
    }
}
